package database;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;


/**
 * class UserManager - provide API of queries of the users table
 */
public class UserManager {

	private Session session;
	 
	/**
	 * constructor
	 * @param session - a session instance
	 */
	 public UserManager(Session session) {
	  this.session = session;
	 }
	 
	 /**
	  * save the user in users table in the DB
	  * @param user - a user
	  */
	 public synchronized void saveUser(User user){
		 System.out.println("save user");
		 System.out.println(user.getUserID());
	  session.save(user);
	  session.flush();
	  session.clear();
	 }
	 
	 /**
	  * @param userID - user id
	  * @return a user according to the user id
	  */
	 public synchronized User getUser(String userID){
		 Query query = session.createQuery("from User");

		 List <User>list = query.list();
		 Iterator<User> it=list.iterator();
		 
		 User user= null;

		 while (it.hasNext()){
		  user=it.next();
		  
		  if (user.getUserID().equals(userID))
			  return user;
		 }
		 
		 return null;	  
	 }
	 
	 /**
	  * update the user in the DB
	  * @param user - a user
	  */
	 public synchronized void  updateUser(User user){
	  session.update(user);
	  session.flush();
	  session.clear();
	 }
	 
	 /**
	  * delete the user from the DB
	  * @param user - a user
	  */
	 public synchronized void deleteUser(User user) {
	  session.delete(user);
	  session.flush();
	  session.clear();
	 }

}
